package mo.tags.stack;

import java.util.Stack;

public class L1209 {

    public String removeDuplicates(String s, int k) {
        Stack<Pair> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (stack.isEmpty() || stack.peek().character != c) {
                stack.push(new Pair(c, 1));
            } else {
                Pair pair = stack.peek();
                if (pair.count + 1 >= k) {
                    stack.pop();
                } else {
                    pair.count++;
                }
            }
        }
        StringBuilder builder = new StringBuilder();
        while (!stack.isEmpty()) {
            Pair pair = stack.pop();
            for (int i = 0; i < pair.count; i++) {
                builder.append(pair.character);
            }
        }
        return builder.reverse().toString();
    }

    private static class Pair {

        public Pair() {
        }

        public Pair(Character character, int count) {
            this.character = character;
            this.count = count;
        }

        private Character character;
        private int count;
    }


    public static void main(String[] args) {
        L1209 test = new L1209();
        System.out.println(test.removeDuplicates("pbbcggttciiippooaais", 2));
    }

}
